package com.sugar.subscribe.course.module.business.service.coachcomment;

import cn.hutool.core.collection.CollUtil;
import com.sugar.subscribe.course.module.business.controller.app.coachcomment.vo.AppCoachCommentPageReqVO;
import com.sugar.subscribe.course.module.business.controller.app.coachcomment.vo.AppCoachCommentRespVO;
import com.sugar.subscribe.course.module.business.controller.app.coachcomment.vo.AppCoachCommentSaveReqVO;
import com.sugar.subscribe.course.module.business.dal.dataobject.coach.CoachDO;
import com.sugar.subscribe.course.module.business.dal.dataobject.coachcommentlike.CoachCommentLikeDO;
import com.sugar.subscribe.course.module.business.dal.mysql.coach.CoachMapper;
import com.sugar.subscribe.course.module.business.dal.mysql.coachcommentlike.CoachCommentLikeMapper;
import com.sugar.subscribe.course.module.business.dal.redis.objlock.ObjectLockRedisDAO;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import com.sugar.subscribe.course.module.business.controller.admin.coachcomment.vo.*;
import com.sugar.subscribe.course.module.business.dal.dataobject.coachcomment.CoachCommentDO;
import com.sugar.subscribe.course.framework.common.pojo.PageResult;
import com.sugar.subscribe.course.framework.common.pojo.PageParam;
import com.sugar.subscribe.course.framework.common.util.object.BeanUtils;

import com.sugar.subscribe.course.module.business.dal.mysql.coachcomment.CoachCommentMapper;

import static com.sugar.subscribe.course.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.sugar.subscribe.course.framework.common.util.collection.CollectionUtils.convertList;
import static com.sugar.subscribe.course.framework.common.util.collection.CollectionUtils.diffList;
import static com.sugar.subscribe.course.module.business.enums.ErrorCodeConstants.*;

/**
 * 评论 Service 实现类
 *
 * @author Ysugar
 */
@Service
@Validated
public class CoachCommentServiceImpl implements CoachCommentService {

    @Resource
    private CoachCommentMapper coachCommentMapper;
    @Resource
    private CoachCommentLikeMapper coachCommentLikeMapper;

    @Resource
    private CoachMapper coachMapper;

    @Resource
    private ObjectLockRedisDAO redisLockDAO;

    @Override
    public Long createCoachComment(CoachCommentSaveReqVO createReqVO) {
        // 插入
        CoachCommentDO coachComment = BeanUtils.toBean(createReqVO, CoachCommentDO.class);
        coachCommentMapper.insert(coachComment);

        // 返回
        return coachComment.getId();
    }

    @Override
    public void updateCoachComment(CoachCommentSaveReqVO updateReqVO) {
        // 校验存在
        validateCoachCommentExists(updateReqVO.getId());
        // 更新
        CoachCommentDO updateObj = BeanUtils.toBean(updateReqVO, CoachCommentDO.class);
        coachCommentMapper.updateById(updateObj);
    }

    @Override
    public void deleteCoachComment(Long id) {
        // 校验存在
        validateCoachCommentExists(id);
        // 删除
        coachCommentMapper.deleteById(id);
    }

    @Override
        public void deleteCoachCommentListByIds(List<Long> ids) {
        // 删除
        coachCommentMapper.deleteByIds(ids);
        }


    private CoachCommentDO validateCoachCommentExists(Long id) {
        CoachCommentDO coachCommentDO = coachCommentMapper.selectById(id);
        if (coachCommentDO == null) {
            throw exception(COACH_COMMENT_NOT_EXISTS);
        }
        return coachCommentDO;
    }

    @Override
    public CoachCommentDO getCoachComment(Long id) {
        return coachCommentMapper.selectById(id);
    }

    @Override
    public PageResult<CoachCommentRespVO> getCoachCommentPage(CoachCommentPageReqVO pageReqVO) {
        return coachCommentMapper.selectPage(pageReqVO);
    }

    @Override
    public void auditCoachComment(CoachCommentAuditReqVO auditReqVO) {
        // 获取评论信息
        CoachCommentDO coachCommentDO = validateCoachCommentExists(auditReqVO.getId());

        Integer auditStatus = auditReqVO.getAuditStatus();
        if (auditStatus.equals(10)) {
            auditReqVO.setRefuseCause("");
        }

        coachCommentMapper.update(CoachCommentDO::getId, auditReqVO.getId(),
                CoachCommentDO::getAuditStatus, auditStatus, CoachCommentDO::getRefuseCause, auditReqVO.getRefuseCause());

        // 统计当前教练的总评分，并更新
        BigDecimal avgScore = coachCommentMapper.getNowCoachAvgScore(coachCommentDO.getCoachId());
        if (avgScore != null)
            coachMapper.update(CoachDO::getId, coachCommentDO.getCoachId(), CoachDO::getTotalScore, avgScore);
    }

    @Override
    public void appCreateCoachComment(AppCoachCommentSaveReqVO createReqVO, Long userId) {
        // 插入
        CoachCommentDO coachComment = BeanUtils.toBean(createReqVO, CoachCommentDO.class);
        coachComment.setUserId(userId).setAuditStatus(0);
        coachCommentMapper.insert(coachComment);
    }

    @Override
    public void appDeleteCoachComment(Long id, Long userId) {
        CoachCommentDO coachCommentDO = validateCoachCommentExists(id);

        if (!coachCommentDO.getUserId().equals(userId))
            throw exception(NO_PERMISSION);

        coachCommentMapper.deleteById(id);
        // 删除评论点赞
        coachCommentLikeMapper.delete(CoachCommentLikeDO::getCommentId, id);
    }

    @Override
    public PageResult<AppCoachCommentRespVO> appGetCoachCommentPage(AppCoachCommentPageReqVO pageReqVO, Long userId) {
        PageResult<AppCoachCommentRespVO> pageResult = coachCommentMapper.appSelectPage(pageReqVO);

        for (AppCoachCommentRespVO respVO : pageResult.getList()) {
            // 判断是否是用户自己的
            respVO.setCanDelete(respVO.getUserId().equals(userId));
            // 判断自己是否点赞
            respVO.setIsLiked(coachCommentLikeMapper.selectCount(CoachCommentLikeDO::getUserId, userId, CoachCommentLikeDO::getCommentId, respVO.getId()) > 0);
        }
        return pageResult;
    }

    @Override
    public void likeComment(Long id, Long userId) {
        redisLockDAO.lock(userId, 10000L, () -> {
            // 查询是否已经点赞
            CoachCommentLikeDO likeInfo = coachCommentLikeMapper.selectOne(CoachCommentLikeDO::getUserId, userId, CoachCommentLikeDO::getCommentId, id);
            if (likeInfo != null){
                coachCommentLikeMapper.deleteById(likeInfo.getId());
            }else {
                coachCommentLikeMapper.insert(new CoachCommentLikeDO().setUserId(userId).setCommentId(id));
            }
        });
    }

    @Override
    public PageResult<AppCoachCommentRespVO> appCoachGetCoachCommentPage(PageParam pageParam, Long coachId) {
        return coachCommentMapper.appSelectPage(BeanUtils.toBean(pageParam, AppCoachCommentPageReqVO.class).setCoachId(coachId));
    }

}